package com.hfb.io.http;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;

/**
 * @author HFB
 * @date 2022-06-16
 */
public class HttpServer {

    private final int port;
    public HttpServer(int port){
        this.port = port;
    }

    public static void main(String[] args) throws InterruptedException {
        if(args.length != 1){
            System.err.println(
                "Usage" +
                HttpServer.class.getSimpleName() +
                "port>");
            return;
        }
        int port = Integer.parseInt(args[0]);
        new HttpServer(port).start();
    }

    private void start() throws InterruptedException {
        ServerBootstrap b = new ServerBootstrap();
        NioEventLoopGroup group = new NioEventLoopGroup();
        b.group(group)
            .channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>(){
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    System.out.println("initChannel ch:" + ch);
                    ch.pipeline()
                        .addLast("Decoder", new HttpRequestDecoder())   // 1
                        .addLast("Encoder", new HttpResponseEncoder())  // 2
                        .addLast("Aggregator", new HttpObjectAggregator(512 * 1024))  // 3
//                        .addLast("handler", new HttpServerUpgradeHandler()    // 4
                        ;
                }
            })
            .option(ChannelOption.SO_BACKLOG, 128)
            .childOption(ChannelOption.SO_KEEPALIVE, Boolean.TRUE);

        ChannelFuture sync = b.bind(port).sync();

        System.out.println("ChannelFuture : " + sync);

    }
}
